#!/usr/bin/env python 
# -*- coding: utf-8 -*-

import re
import pymysql
import requests

def async_from_api():
    """
    从API中同步游戏到工作台
    :param file_path:
    :return:
    """
    url = "http://4399sy.com/api/game/datalist?ts=1515646208&sign=81eab60944fe26c12bc64720448eb412"
    response = requests.get(url)
    game_list = []
    if response.status_code == 200:
        game_list = response.json()
    db = pymysql.connect("xx.xx.xxx.xxx", "root", "123456", "ptqa_workbench",use_unicode=True, charset="utf8")
    cursor = db.cursor(pymysql.cursors.DictCursor)
    flag = True
    add_list = []
    error_msg=[]
    try:
        for game in game_list:
            client_id = game.get('client_id')
            game_name = game.get('game_short') + "_" + game.get('game_name')
            os_id = game.get('os_id')
            game_type = None
            if os_id == "2":
                game_type = "android"
                game_name = game_name + "-安卓"
            if os_id == "1":
                game_type = "iOS"
                game_name = game_name + "-iOS"
            if os_id == "3":
                game_type = "iOS"
                game_name = game_name + "-iOS越狱"
            check_sql = "SELECT * from pkg_game WHERE client_id='%s'" % (client_id)
            try:
                cursor.execute(check_sql)
                result = cursor.fetchone()
                if not result:
                    insert_sql = "INSERT INTO pkg_game(game_type,name,client_id) VALUES('%s','%s','%s')" % (
                        game_type, game_name, client_id)
                    try:
                        cursor.execute(insert_sql)
                        db.commit()
                        add_list.append(
                            "本次同步新增游戏数据:client_id=%s,name=%s,game_type=%s" % (
                                client_id, game_name, game_type))
                        # print( "本次同步新增游戏数据:client_id=%s,name=%s,game_type=%s" % (client_id, game_name, game_type))
                        flag = False
                    except Exception as e:
                        error_msg.append("新增数据时失败了,新增语句为:%s" %insert_sql)
                        print(e)
                        db.rollback()

            except Exception as e:
                error_msg.append("查询数据时就失败了，查询语句为：%s" %check_sql)
                print(e)
    finally:
        db.close()

    if flag:
        add_list.append("本次同步没有新增数据")
        # print("本次同步没有新增数据")
    add_list.append("数据同步完成！")
    add_list.extend(error_msg)
    # print("数据同步完成！")
    return add_list



